var express = require("express");
var bodyParser = require('body-parser'); //解析请求参数
const ReconnectableRSocket = require("./rsocket/rsocket-rxjs.js");
const fs = require("fs");
// 引入Multer处理multipart/form-data类型数据
const multer = require('multer');
const Logger = require("./setLog.js");
var rsocket;
// 读取文件获取后台ip及端口
function getTcpServerInfo() {
	fs.readFile("./info.txt", "utf-8", function(error, data) {
		// console.log(error);  //如果err为null就说明读取成功了,没有出错
		// console.log(data); // 如果不给第二个参数[读取的文件编码格式]就会以beffer格式输出
		//  用error来判断文件是否读取成功
		if (error) return Logger.error("读取文件失败,内容是" + error.message);
		let info = data.split(/\s+/);
		Logger.info("tcp服务端信息：")
		Logger.info(info);
		rsocket = new ReconnectableRSocket({
			host: info[0],
			port: info[1]
		})
	});
}
getTcpServerInfo();
var httpApp = express();
/*
// 设置保存上传文件路径(下载到本地)
 const upload = multer({
	dest: './static/upload'
}) */
httpApp.use(bodyParser.urlencoded({
	extended: false
}))
// 处理表单提交，对应请求头application/x-www-form-urlencoded
httpApp.use(bodyParser.urlencoded({
	extended: false // 为true时将使用qs库处理数据，通常不需要
}))
// 处理fetch请求，对应请求头application/json
httpApp.use(bodyParser.json());
const upload=multer();
/* 
// 处理上传文件
httpApp.use(upload); */



//设置允许跨域访问该服务.
httpApp.all('*', function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
	//Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
	res.header('Access-Control-Allow-Headers', 'Content-Type');
	res.header('Access-Control-Allow-Methods', '*');
	res.header('Content-Type', 'application/json;charset=utf-8');
	next();
});
httpApp.get("/echo", function(req, res) {
	// let params = req.body;
	let params2 = req.query;
	let data=params2.data;
	if(typeof(data)=="string"){
		data=JSON.parse(data);
	}
	if(data==0){
		data="ceshi";
	}
	console.log(data)
	Logger.info(params2);
	let matada=params2.matada;
	if(!matada){
		res.send({
			code: 500,
			msg: "传输数据有误"
		})
		return;
	}
	rsocket.requestResponse(JSON.stringify(data), matada).then((data) => {
		rsocket.closeSocket();
		if(typeof(data)=="string"){
			data=JSON.parse(data);
		}
		console.log("返回")
		console.log(data);
		res.send(data);
	}, error => {
		console.log(error)
		res.send({
			code: 500,
			msg: "服务器端出错"
		})
		rsocket.closeSocket();
	});
});
httpApp.get("/list", function(req, res) {
	// let params = req.body;
	let params2 = req.query;
	Logger.info(params2);
	rsocket.requestResponse(JSON.stringify(params2), "message.list").then((data) => {
		rsocket.closeSocket();
		res.send({
			code: 200,
			data: data
		})
	}, error => {
		res.send({
			code: 500,
			msg: "服务器端出错"
		})
		rsocket.closeSocket();
	});
});
httpApp.post("/file", upload.fields([{name: 'file'}]),function(req, res) {
	let inputFiles = req.files;
	let oneFile=inputFiles['file'][0];
	let fileName=oneFile.originalname;
	let fileBuffer=oneFile.buffer;
	let route="v1.core.upload."+Buffer.from(fileName).toString("base64");
	rsocket.requestResponse(fileBuffer, route,1).then((data) => {
		rsocket.closeSocket();
		res.send({
			code: 200,
			data: data
		})
	}, error => {
		console.log(error)
		res.send({
			code: 500,
			msg: "服务器端出错"
		})
		rsocket.closeSocket();
	});
});
async function runData() {
	httpApp.listen('8002', () => {
		Logger.info('监听端口 8001')
	})
}

function exitData() {
	process.exit(1)
}
runData();
// module.exports={
//  	runData,exitData
// }
